<template>
  <el-container v-loading="loading">
    <div style="width: 100%" :class="{ 'process-design': activeSelect === 'processDesign' }">
        <el-header style="background: white; position: sticky; width: 100%; z-index: 99">
            <layout-header 
                v-model="activeSelect" 
                @publish="publishProcess" 
                @save="save"
            ></layout-header>
        </el-header>
        <div class="layout-body">
            <form-design ref="formSetting" v-show="activeSelect === 'formSetting'"/>
            <process-design ref="processDesign" v-show="activeSelect === 'processDesign'"/>
        </div>
        <w-dialog :showFooter="false" v-model="validVisible" title="设置项检查">
            <el-steps align-center :active="validStep" finish-status="success">
            <el-step v-for="(step, i) in validOptions" :title="step.title" :key="i" :icon="step.icon" :status="step.status" :description="step.description"/>
            </el-steps>
            <el-result :icon="validIcon" :title="errTitle" :subTitle="validResult.desc">
                <template #icon>
                    <el-icon style="font-size: 30px" v-if="!validResult.finished"><Loading /></el-icon>
                </template>
                <template #sub-title>
                    <div class="err-info" v-if="validResult.errs.length > 0">
                        <ellipsis hover-tip v-for="(err, i) in validResult.errs" :key="i + '_err'" :content="err">
                            <template #pre>
                                <el-icon><Warning /></el-icon>
                            </template>
                        </ellipsis>
                    </div>
                </template>
                <template #extra>
                    <el-button type="primary" v-if="validResult.finished" @click="doAfter">
                    {{ validResult.action }}
                    </el-button>
                </template>
            </el-result>
        </w-dialog>
    </div>
  </el-container>
</template>

<script>
import { reactive, computed, toRefs, ref, onMounted } from 'vue'
import { useWorkFlowConfig } from '/@/stores/workFlow'
import { storeToRefs } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { isNotEmpty } from '/@/utils/utils'
import LayoutHeader from './components/LayoutHeader.vue'
import FormDesign from './components/FormDesign.vue'
import ProcessDesign from './components/ProcessDesign.vue'
import { Loading, Warning } from '@element-plus/icons-vue'

export default {
    name: 'WorkFlow',
    components: {
        LayoutHeader,
        FormDesign,
        ProcessDesign,
        Loading,
        Warning
    },
    setup() {
        const route = useRoute()
        const router = useRouter()
        const storesWorkFlowConfig = useWorkFlowConfig()
        const workFlowConfig = storeToRefs(storesWorkFlowConfig)
        const formSetting = ref()
        const processDesign = ref()
        const state = reactive({
            isNew: true,
            validStep: 0,
            timer: null,
            loading: false,
            activeSelect: 'formSetting',
            validVisible: false,
            isSave: false,
            validResult: {},
            validOptions: [
                {title: '审批表单', description: '', icon: '', status: ''},
                {title: '审批流程', description: '', icon: '', status: ''},
            ],
            validComponents: [
                'formSetting',
                'processDesign'
            ],
            valids: []
        })
        const setedup = computed(() => {
            return workFlowConfig.design
        })
        const errTitle = computed(() => {
            if (state.validResult.finished && !state.validResult.success && state.validResult.errs.length > 0) {
                return (state.validResult.title + ` (${state.validResult.errs.length}项错误) 😥`)
            }
            return state.validResult.title
        })
        const publishProcess = () => {
            validateDesign()
        }
        const save = () => {
            doSave()
        }
        const doSave = (call) => {
            if (Array.isArray(state.valids) && state.valids.length === 0) {
                let modelData = getDataFromStore()
                state.loading = true
                // TO DO 接口
                return 
                saveProcess(modelData).then(rsp => {
                    state.loading = false
                    state.isSave = true
                    ElMessage.success("保存成功")
                    if (call){
                        state.loading = true
                        call(modelData.groupId, rsp.data)
                        state.loading = false
                    }
                    createReload(modelData.groupId, rsp.data)
                }).catch(err => {
                    state.loading = false
                    this.$err(err, '抄送我的')
                    ElMessage.error(
                        err.response.data.message || err.response.data
                    )
                })
            }else {
                ElMessage.warning(String(state.valids))
            }
        }
        const validateDesign = () => {
            state.validVisible = true
            state.validStep = 0
            showValiding()
            stopTimer()
            state.timer = setInterval(async () => {
                if(state.validStep == 0) {
                    state.validResult.errs = await formSetting.value.validate()
                }else{
                    state.validResult.errs = await processDesign.value.validate()
                    console.log('process: ', state.validResult.errs)
                }
                console.log(state.validResult)
                if (Array.isArray(state.validResult.errs) && state.validResult.errs.length === 0) {
                    if (state.validStep >= state.validOptions.length) {
                        stopTimer()
                        showValidFinish(true)
                    }
                    state.validStep++
                } else {
                    stopTimer()
                    state.validOptions[state.validStep].status = 'error'
                    showValidFinish(false, getDefaultValidErr())
                }
            }, 300)
        }
        const showValiding = () => {
            state.validResult = {
                errs: [],
                finished: false,
                success: false,
                title: '检查中...',
                action: '处理',
                desc: '正在检查设置项',
            }
            state.validStep = 0
            state.validOptions.forEach((op) => {
                op.status = ''
                op.icon = ''
                op.description = ''
            })
        }
        const stopTimer = () => {
            if (state.timer) {
                clearInterval(state.timer)
            }
        }
        const showValidFinish = (success, err) => {
            state.validResult.success = success
            state.validResult.finished = true
            state.validResult.title = success ? '校验完成 😀' : '校验失败 '
            state.validResult.desc = success ? '设置项校验成功，是否提交？' : err
            state.validResult.action = success ? '提 交' : '去修改'
        }
        const getDefaultValidErr = () => {
            switch (state.validStep) {
                case 0:
                    return '请检查基础设置项'
                case 1:
                    return '请检查审批表单相关设置'
                case 2:
                    return '请检查审批流程，查看对应标注节点错误信息'
                case 3:
                    return '请检查扩展设置'
                default:
                    return '未知错误'
            }
        }
        const getDataFromStore = () => {
            return {
                formId: setedup.value.formId,
                formName: setedup.value.formName,
                logo: JSON.stringify(setedup.value.logo),
                settings: JSON.stringify(setedup.value.settings),
                groupId: setedup.value.groupId,
                formItems: JSON.stringify(setedup.value.formItems),
                formConfig: JSON.stringify(setedup.value.formConfig || {}),
                process: JSON.stringify(setedup.value.process),
                remark: setedup.value.remark,
            }
        }
        const createReload = (groupId, formId) => {
            if(!isNotEmpty(route.query.code)){
                window.location.replace(`${window.location.origin}/#/workflow?groupId=${groupId}&code=${formId}`)
                window.location.reload()
            }
        }
        const loadInitFrom = () => {
            storesWorkFlowConfig.loadForm({
                formId: null,
                formName: '未命名表单',
                logo: {
                    icon: 'ele-Eleme',
                    background: '#1e90ff',
                },
                settings: {
                    commiter: [],
                    admin: [],
                    sign: false,
                    notify: {
                        types: ['APP'],
                        title: '消息通知标题',
                    }
                },
                groupId: undefined,
                formItems: [],
                formConfig: getDfFormConfig(),
                process: {
                    id: 'root',
                    parentId: null,
                    type: 'ROOT',
                    name: '发起人',
                    desc: '任何人',
                    props: {
                        assignedUser: [],
                        formPerms: [],
                    },
                    children: {}
                },
                remark: '备注说明'
            })
        }
        const getDfFormConfig = () => {
            return {
                labelPos: "top",
                ruleType: "SIMPLE",
                labelWidth: "",
                rules: [],
                ruleJs: "//formData: 表单数据  formMap: 表单字段id -> 字段json配置\r\nfunction doChange(formData, formMap){\r\n\t\r\n}"
            }
        }
        const loadFormInfo = (formId) => {
            state.loading = true
            // TO DO 这里是接口 
            return
            getNewVerProcess(formId).then((rsp) => {
                state.loading = false
                let form = rsp.data
                form.logo = JSON.parse(form.logo)
                form.settings = JSON.parse(form.settings)
                form.formItems = JSON.parse(form.formItems)
                form.formConfig = form.formConfig ? JSON.parse(form.formConfig): getDfFormConfig()
                form.process = JSON.parse(form.process)
                storesWorkFlowConfig.loadForm('form')
            }).catch((err) => {
                state.loading = false
                ElMessage.error('获取流程信息失败')
            })
        }
        const doAfter = () => {
            if (state.validResult.success) {
                doPublish()
            } else {
                state.activeSelect = state.validComponents[state.validStep]
                state.validVisible = false
            }
        }
        const doPublish = () => {
            ElMessageBox.confirm('如果您只想临时保存请选择保存，确认发布后流程立即生效，是否继续?', '提示', {
                confirmButtonText: '发布',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                state.validVisible = false
                doSave((groupId, formId) => {
                state.isSave = true
                // TO DO 接口
                return 
                    deployProcess(formId).then(rsp => {
                        state.loading = false
                        ElMessageBox.confirm('发布成功，您想继续留在本页还是返回表单列表呢', '操作成功', {
                            confirmButtonText: '留在本页',
                            cancelButtonText: '返回列表',
                            type: 'success'
                        }).then(() => {
                            createReload(groupId, formId)
                        }).catch(() => {
                            router.go("-1")
                        })
                    }).catch(err => {
                        ElMessage.error(err.msg || '部署流程失败')
                    })
                })
            })
        }
        onMounted(() => {
            showValiding()
            const formId = route.query.code
            loadInitFrom()
            if (isNotEmpty(formId)) {
                state.isNew = false
                loadFormInfo(formId)
            }
            let group = route.query.groupId
            setedup.groupId = isNotEmpty(group) ? parseInt(group) : null
        })
        return {
            ...toRefs(state),
            publishProcess,
            save,
            formSetting,
            processDesign,
            setedup,
            errTitle,
            doAfter
        }
    }
}
</script>

<style lang="scss" scoped>
.layout-body {
  min-width: 980px;
}

:deep(.el-step) {
  .is-success {
    color: var(--el-color-primary);
    border-color: var(--el-color-primary);
  }
}

:deep(.el-result) {
  .icon-success {
    fill: var(--el-color-success);
  }

  .icon-warning {
    fill: var(--el-color-warning);
  }
}

.err-info{
  max-height: 180px;
  overflow-y: auto;
  & > div{
    padding: 5px;
    margin: 2px 0;
    width: 250px;
    text-align: left;
    border-radius: 3px;
    background: rgb(242 242 242);
  }
  :deep(.icon){
    margin: 0 5px;
  }
}
:deep(.el-header){
    padding: 0;
}
</style>